package erbedo.call.tracker;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class Stats extends Activity {

	final String LOG_TAG = "Stats";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stats);

		Intent i = getIntent();
		String filter = i.getStringExtra("FILTER_STRING");

		TextView tv_totalCall = (TextView)findViewById(R.id.total_call_time);
		TextView tv_longestCall = (TextView)findViewById(R.id.longest_call);
		TextView tv_averageCall = (TextView)findViewById(R.id.average_call);
		TextView tv_callCount = (TextView)findViewById(R.id.call_count);

		TextView tv_totalCallWeek = (TextView)findViewById(R.id.week_call_time);
		TextView tv_longestCallWeek = (TextView)findViewById(R.id.longest_call_week);
		TextView tv_averageCallWeek = (TextView)findViewById(R.id.average_call_week);
		TextView tv_callCountWeek = (TextView)findViewById(R.id.call_count_week);

		TextView tv_totalCallMonth = (TextView)findViewById(R.id.month_call_time);
		TextView tv_longestCallMonth = (TextView)findViewById(R.id.longest_call_month);
		TextView tv_averageCallMonth = (TextView)findViewById(R.id.average_call_month);
		TextView tv_callCountMonth = (TextView)findViewById(R.id.call_count_month);

		GregorianCalendar gcal = new GregorianCalendar();
		int fdw = gcal.getFirstDayOfWeek();

		gcal.setGregorianChange(new Date());
		int thisday = gcal.getTime().getDay();
		int offset = thisday - fdw;
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DATE, -offset);		
		long firstDayThisWeek = c.getTimeInMillis();

		offset = c.get(Calendar.DATE) + 1;
		c.add(Calendar.DATE, -offset);
		long firstDayOfMonth = c.getTimeInMillis();

		Cursor cursorAllTime;
		Cursor cursorWeek;
		Cursor cursorMonth;
		if (filter.equals("ALL CALLS")) {
			cursorAllTime = getContentResolver().query(
					android.provider.CallLog.Calls.CONTENT_URI, 
					null, null, null, 
					android.provider.CallLog.Calls.DATE + " DESC");

			cursorWeek = getContentResolver().query(
					android.provider.CallLog.Calls.CONTENT_URI, 
					null, 
					"date > " + String.valueOf(firstDayThisWeek),
					null, 
					android.provider.CallLog.Calls.DATE + " DESC");

			cursorMonth = getContentResolver().query(
					android.provider.CallLog.Calls.CONTENT_URI, 
					null, 
					"date > " + String.valueOf(firstDayOfMonth),
					null, 
					android.provider.CallLog.Calls.DATE + " DESC");

		} else {
			String[] q = new String[] {"%" + filter + "%"};
			cursorAllTime = getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI,
					null, CallLog.Calls.NUMBER + " LIKE ?",
					q, android.provider.CallLog.Calls.DATE + " DESC");

			cursorWeek = getContentResolver().query(
					android.provider.CallLog.Calls.CONTENT_URI, 
					null, 
					"date > " + String.valueOf(firstDayThisWeek)
					+ ") AND (" +
					CallLog.Calls.NUMBER + " LIKE ?",
					q, 
					android.provider.CallLog.Calls.DATE + " DESC");

			cursorMonth = getContentResolver().query(
					android.provider.CallLog.Calls.CONTENT_URI, 
					null, 
					"date > " + String.valueOf(firstDayOfMonth)
					+ ") AND (" +
					CallLog.Calls.NUMBER + " LIKE ?",
					q,
					android.provider.CallLog.Calls.DATE + " DESC");
		}
		startManagingCursor(cursorAllTime);
		if (cursorAllTime.getCount() > 0 ){
			cursorAllTime.moveToFirst();
			int duration = 0;
			int max = -1;

			while (!cursorAllTime.isLast()) {
				Log.i(LOG_TAG,"CYCLING");
				try {
					int value = cursorAllTime.getInt(cursorAllTime.getColumnIndex("duration"));
					duration += value;
					if (value > max) {
						max = value;
					}
				} catch (Exception e) {
					Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
				}
				cursorAllTime.moveToNext();
			}
			double avg = duration / cursorAllTime.getCount();

			tv_callCount.append(String.valueOf(cursorAllTime.getCount()));
			tv_totalCall.append(formatIntoMMSS(duration));
			tv_longestCall.append(formatIntoMMSS(max));
			tv_averageCall.append(formatIntoMMSS(avg));
		} else {
			tv_callCount.append("no data");
			tv_totalCall.append("no data");
			tv_longestCall.append("no data");
			tv_averageCall.append("no data");
		}

		startManagingCursor(cursorWeek);
		if (cursorWeek.getCount() > 0 ){
			cursorWeek.moveToFirst();
			int duration = 0;
			int max = -1;

			while (!cursorWeek.isLast()) {
				Log.i(LOG_TAG,"CYCLING");
				try {
					int value = cursorWeek.getInt(cursorWeek.getColumnIndex("duration"));
					duration += value;
					if (value > max) {
						max = value;
					}
				} catch (Exception e) {
					Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
				}
				cursorWeek.moveToNext();
			}
			double avg = duration / cursorWeek.getCount();
			tv_callCountWeek.append(String.valueOf(cursorWeek.getCount()));
			tv_totalCallWeek.append(formatIntoMMSS(duration));
			tv_longestCallWeek.append(formatIntoMMSS(max));
			tv_averageCallWeek.append(formatIntoMMSS(avg));
		} else {
			tv_callCountWeek.append("no data");
			tv_totalCallWeek.append("no data");
			tv_longestCallWeek.append("no data");
			tv_averageCallWeek.append("no data");
		}

		startManagingCursor(cursorMonth);
		if (cursorMonth.getCount() > 0 ){
			cursorMonth.moveToFirst();
			int duration = 0;
			int max = -1;

			while (!cursorMonth.isLast()) {
				Log.i(LOG_TAG,"CYCLING");
				try {
					int value = cursorMonth.getInt(cursorMonth.getColumnIndex("duration"));
					duration += value;
					if (value > max) {
						max = value;
					}
				} catch (Exception e) {
					Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
				}
				cursorMonth.moveToNext();
			}
			double avg = duration / cursorMonth.getCount();
			tv_callCountMonth.append(String.valueOf(cursorMonth.getCount()));
			tv_totalCallMonth.append(formatIntoMMSS(duration));
			tv_longestCallMonth.append(formatIntoMMSS(max));
			tv_averageCallMonth.append(formatIntoMMSS(avg));
		} else {
			tv_callCountMonth.append("no data");
			tv_totalCallMonth.append("no data");
			tv_longestCallMonth.append("no data");
			tv_averageCallMonth.append("no data");
		}
	}

	private static String formatIntoMMSS(double secsIn) {

		int minutes = (int)(Math.floor(secsIn / 60));
		String min;
		if (minutes == 0)
			min = ""; 
		else if (minutes < 10)
			min = "0" + String.valueOf(minutes) + " min. and ";
		else
			min = String.valueOf(minutes) + " min. and ";

		int seconds = (int)(secsIn - (minutes * 60));
		String sec;
		if (seconds == 0) 
			sec = "no data";
		else
			sec = String.valueOf(seconds) + " seconds.";

		return min + sec;
	}
}